import { defineStore } from "pinia";
import { ref } from "vue";
import {login} from "../service/administrator/administrator";
import { LoginData } from "../service/administrator/type";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

// export const useStore = defineStore('index',{
//     state:()=>({
//        token:"",
//        menus:[]
//     }),
//     actions:{
//         updataToken(val:string){
//             this.token=val
//         },
//         updataMenus(val:any){
//             this.menus=val
//         }
//     }
// });

export const useStore = defineStore('index', () => {
    const token = ref("")
    const menus = ref([])
    const router = useRouter()
    const updataToken = (val: string) => {
        token.value = val
    }
    const updataMenus = (val: any) => {
        menus.value = val
    }

    const logining =  (data: LoginData) => {

        return new Promise(async(resolve, reject)=>{
            const res:any = await login(data)
            if (res.errCode === 10000) {
                token.value = res.data.token
                menus.value = res.data.menu
                router.push('/')
                resolve(res)
            }
            else{
                ElMessage(res.errMsg)
                reject(res.errMsg)
            }
        })
       
    }

    return { token, menus, updataToken, updataMenus,logining }

}, {
    persist: {
        storage: sessionStorage
    }
})